export class CustomEventSource {
  private url: string
  private options: {
    headers?: Record<string, string>
    withCredentials?: boolean
  }
  private controller: AbortController | null = null

  constructor(url: string, options: {
    headers?: Record<string, string>
    withCredentials?: boolean
  } = {}) {
    this.url = url
    this.options = options
  }

  connect() {
    this.controller = new AbortController()

    // 创建带认证头的请求
    fetch(this.url, {
      method: 'GET', // 明确指定为 GET 请求
      headers: {
        'Accept': 'text/event-stream',
        ...this.options.headers
      },
      credentials: this.options.withCredentials ? 'include' : 'same-origin',
      signal: this.controller.signal
    }).then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      if (!response.body) {
        throw new Error('No response body')
      }

      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      let buffer = ''

      const processText = (text: string) => {
        const lines = text.split('\n')
        for (const line of lines) {
          // 处理事件类型
          if (line.startsWith('event:')) {
            const eventType = line.slice(6).trim()
            console.log('SSE event type:', eventType)
            continue
          }
          // 处理数据
          if (line.startsWith('data:')) {
            const data = line.slice(5).trim()
            if (data) {
              console.log('SSE data received:', data)
              // 创建消息事件，保持原始数据格式
              const event = new MessageEvent('message', { data })
              this.onmessage?.(event)
            }
          }
        }
      }

      const read = () => {
        reader.read().then(({done, value}) => {
          if (done) {
            console.log('SSE connection closed')
            this.onclose?.()
            return
          }

          const chunk = decoder.decode(value, { stream: true })
          console.log('SSE received chunk:', chunk)
          buffer += chunk
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''
          processText(lines.join('\n'))
          read()
        }).catch(error => {
          if (error.name === 'AbortError') {
            console.log('SSE connection aborted')
          } else {
            console.error('SSE read error:', error)
            this.onerror?.(error)
          }
        })
      }

      read()
    }).catch(error => {
      if (error.name !== 'AbortError') {
        console.error('SSE connection error:', error)
        this.onerror?.(error)
      }
    })
  }

  onmessage?: (event: MessageEvent) => void
  onerror?: (error: any) => void
  onclose?: () => void

  close() {
    console.log('Closing SSE connection')
    if (this.controller) {
      this.controller.abort()
      this.controller = null
    }
  }
} 